import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Icon,
  Button,
  Modal,
  Divider,
  TreeSelect,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from './GoodsList.less';

const FormItem = Form.Item;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ brand, loading }) => ({
  brand,
  loading: loading.models.brand,
}))
@Form.create()
class CreateForm extends PureComponent {
  state = {
    formVals: {
      name: [],
      c_name: [],
    },
    currentStep: 0,
  };
  constructor(props) {
    super(props);
    this.formLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 13 },
    };
  }

  handleNext = currentStep => {
    const { form, handleAdd } = this.props;
    const { formVals: oldValue } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formVals = { ...oldValue, ...fieldsValue };
      this.setState({ formVals }, () => {
        handleAdd(formVals);
      });
    });
  };

  sontypeData = e => {
    const { dispatch } = this.props;
    this.state.father_id = e;
    dispatch({
      type: 'brand/fetchbrandlist',
      payload: {
        father_id: e,
      },
    });
  };

  brandData = e => {
    const { dispatch } = this.props;
    this.state.formVals.brand_id = 0;
    dispatch({
      type: 'brand/fetchbrandlist',
      payload: {
        son_id: e,
        father_id: this.state.father_id,
      },
    });
  };

  renderContent = formVals => {
    const { form } = this.props;
    const {
      brand: { treeData },
    } = this.props;
    return [
      <FormItem key="name" {...this.formLayout} label="品牌名称">
        {form.getFieldDecorator('name', {
          rules: [{ required: true, message: '请输入标题！' }],
          initialValue: formVals.name,
        })(<Input placeholder="请输入" />)}
      </FormItem>,

      <FormItem key="c_name" {...this.formLayout} label="所属分类">
        {form.getFieldDecorator('c_name', {
          rules: [{ required: true, message: '请输入产地！' }],
          initialValue: formVals.c_name,
        })(
          <TreeSelect
            style={{ width: 300 }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={treeData}
            placeholder="请选择分类"
            treeDefaultExpandAll
          />
        )}
      </FormItem>,
    ];
  };

  renderFooter = () => {
    const { handleModalVisible } = this.props;
    return [
      <Button key="cancel" onClick={() => handleModalVisible()}>
        取消
      </Button>,
      <Button key="submit" type="primary" onClick={() => this.handleNext()}>
        完成
      </Button>,
    ];
  };

  render() {
    const { modalVisible, form, handleAdd, handleModalVisible } = this.props;
    const okHandle = () => {
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        form.resetFields();
        handleAdd(fieldsValue);
      });
    };
    const { formVals, currentStep } = this.state;
    return (
      <Modal
        width={640}
        bodyStyle={{ padding: '32px 40px 48px' }}
        destroyOnClose
        title="新建品牌"
        visible={modalVisible}
        footer={this.renderFooter(currentStep)}
        onOk={okHandle}
        onCancel={() => handleModalVisible()}
      >
        {this.renderContent(formVals)}
      </Modal>
    );
  }
}

@connect(({ brand, loading }) => ({
  brand,
  loading: loading.models.brand,
}))
@Form.create()
class UpdateForm extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      formVals: {
        key: props.values.key,
        name: props.values.name,
        c_name: props.values.c_name,
        c_id: props.values.c_id,
        created_at: props.values.created_at,
      },
      currentStep: 0,
    };

    this.formLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 13 },
    };
  }

  handleNext = () => {
    const { form, handleUpdate } = this.props;
    const { formVals: oldValue } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formVals = { ...oldValue, ...fieldsValue };
      this.setState(
        {
          formVals,
        },
        () => {
          handleUpdate(formVals);
        }
      );
    });
  };

  renderContent = (currentStep, formVals) => {
    const {
      form,
      brand: { treeData },
    } = this.props;
    return [
      <FormItem key="key">
        {form.getFieldDecorator('key', {
          initialValue: formVals.key,
        })(<Input type="hidden" placeholder="请输入" />)}
      </FormItem>,

      <FormItem key="name" {...this.formLayout} label="品牌名称">
        {form.getFieldDecorator('name', {
          rules: [{ required: true, message: '请输入标题！' }],
          initialValue: formVals.name,
        })(<Input placeholder="请输入" />)}
      </FormItem>,

      <FormItem key="c_id" {...this.formLayout} label="所属分类">
        {form.getFieldDecorator('c_id', {
          rules: [{ required: true, message: '请输入产地！' }],
          initialValue: formVals.c_id,
        })(
          <TreeSelect
            style={{ width: 300 }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={treeData}
            placeholder="Please select"
            treeDefaultExpandAll
          />
        )}
      </FormItem>,
    ];
  };

  renderFooter = currentStep => {
    const { handleUpdateModalVisible } = this.props;
    return [
      <Button key="cancel" onClick={() => handleUpdateModalVisible()}>
        取消
      </Button>,
      <Button key="submit" type="primary" onClick={() => this.handleNext(currentStep)}>
        完成
      </Button>,
    ];
  };

  render() {
    const { updateModalVisible, handleUpdateModalVisible } = this.props;
    const { currentStep, formVals } = this.state;

    return (
      <Modal
        width={640}
        bodyStyle={{ padding: '32px 40px 48px' }}
        destroyOnClose
        title="品牌设置"
        visible={updateModalVisible}
        footer={this.renderFooter(currentStep)}
        onCancel={() => handleUpdateModalVisible()}
      >
        {this.renderContent(currentStep, formVals)}
      </Modal>
    );
  }
}

@connect(({ brand, loading }) => ({
  brand,
  loading: loading.models.brand,
}))
@Form.create()
class Brand extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
    value: undefined,
  };

  columns = [
    {
      title: '品牌名称',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '所属分类',
      dataIndex: 'c_name',
      align: 'center',
    },
    {
      title: '品牌创建时间',
      dataIndex: 'created_at',
      align: 'center',
      sorter: true,
    },
    {
      title: '操作',
      align: 'center',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleUpdateModalVisible(true, record)}>
            <Icon type="edit" theme="twoTone" /> 修改
          </a>
          <Divider type="vertical" />
          <a onClick={() => this.rightListdel(record)}>
            <Icon type="delete" theme="twoTone" /> 删除
          </a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'brand/fetchbrandlist',
    });
  }

  rightListdel = e => {
    const { dispatch } = this.props;
    Modal.confirm({
      title: '删除品牌',
      content: '确定删除该品牌吗？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'brand/branddel',
          payload: {
            id: e.key,
          },
        });
      },
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    console.log(pagination);
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'brand/fetchbrandlist',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'brand/fetchbrandlist',
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    if (!selectedRows) return;
    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'brand/branddel',
          payload: {
            key: selectedRows.map(row => row.key),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
      };

      this.setState({
        formValues: values,
      });
      dispatch({
        type: 'brand/fetchbrandlist',
        payload: values,
      });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      stepFormValues: record || {},
    });
  };

  handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'brand/brandAdd',
      payload: fields,
    });
    this.handleModalVisible();
  };

  handleUpdate = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'brand/brandremove',
      payload: {
        ...fields,
      },
    });
    this.handleUpdateModalVisible();
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      brand: { treeData },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="品牌名称">
              {getFieldDecorator('name')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="所属分类">
              {getFieldDecorator('c_id')(
                <TreeSelect
                  style={{ width: 300 }}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  treeData={treeData}
                  placeholder="请选择"
                  treeDefaultExpandAll
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  onChange = value => {
    console.log(value);
    this.setState({ value });
  };

  render() {
    const {
      brand: { list },
      loading,
    } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, stepFormValues } = this.state;
    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };
    return (
      <PageHeaderWrapper title="品牌管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新建
              </Button>
              {selectedRows.length > 0 && (
                <Button icon="delete" type="danger" onClick={this.handleMenuClick}>
                  批量删除
                </Button>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={list}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} />
        {stepFormValues && Object.keys(stepFormValues).length ? (
          <UpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={stepFormValues}
          />
        ) : null}
      </PageHeaderWrapper>
    );
  }
}

export default Brand;
